package com.black.app.service.impl.exercise;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.app.domain.exercise.AppExercisePersonalize;
import com.black.app.domain.req.exercise.add.AppExercisePersonalizeAddReq;
import com.black.app.domain.req.exercise.edit.AppExercisePersonalizeEditReq;
import com.black.app.domain.req.exercise.query.AppExercisePersonalizeQueryReq;
import com.black.app.domain.resp.exercise.AppExercisePersonalizeResp;
import com.black.app.mapper.exercise.AppExercisePersonalizeMapper;
import com.black.app.service.exercise.AppExercisePersonalizeService;
import com.black.common.exception.database.PrimaryException;
import com.black.common.exception.database.RecordNotFoundException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
* @author L
* @description 针对表【app_exercise_personalize】的数据库操作Service实现
* @createDate 2024-10-23 16:57:08
*/
@Service
public class AppExercisePersonalizeServiceImpl extends ServiceImpl<AppExercisePersonalizeMapper, AppExercisePersonalize>
    implements AppExercisePersonalizeService{

    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public PageInfo<AppExercisePersonalizeResp> paginationQuery(AppExercisePersonalizeQueryReq req) {
        return PageHelper.startPage(req.getPageNum(),req.getPageSize()).doSelectPageInfo(()->{
            this.baseMapper.paginationQuery(req);
        });
    }

    @Override
    public AppExercisePersonalizeResp findById(Long id) {
        AppExercisePersonalizeResp db = this.baseMapper.findById(id);
//        AppExercisePersonalize db = this.getById(id);
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }
//        BeanUtils.copyProperties(db, resp);
//        return resp;
        return db;
    }

    @Override
    public boolean add(AppExercisePersonalizeAddReq req) {
        //检验user_id是否已经存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<AppExercisePersonalize>().eq(AppExercisePersonalize::getUserId, req.getUserId()))) {
            throw new RecordNotFoundException();
        }
        AppExercisePersonalize newEntity = new AppExercisePersonalize();
        BeanUtils.copyProperties(req, newEntity);
        return this.save(newEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Long[] ids) {
        final AppExercisePersonalizeServiceImpl service =this;
        if (Objects.isNull(ids) || ids.length == 0) {
            throw new PrimaryException();
        }
        this.redisTemplate.execute(new SessionCallback<Void>() {
            @Override
            public Void execute(RedisOperations operations) throws DataAccessException {
                // 开启redis事务
                operations.multi();

                // 循环删除，因为数据量不大, 时间复杂度O(n), 事务问题
                try {
                    for (Long id : ids) {
                        AppExercisePersonalize db = service.getById(id);
                        if (Objects.nonNull(db)) {
                            //删除数据库中的值
                            service.removeById(id);
                            //移出缓存中的值
                            String redisKey = " "+db.getPersonalizeId();
                            operations.delete(redisKey);
                        }
                    }
                    // 提交redis事务
                    operations.exec();

                } catch (Exception e) {
                    operations.discard();
                    throw e;
                }
                return null;
            }
        });
        return true;
    }

    @Override
    public boolean edit(AppExercisePersonalizeEditReq req) {
        AppExercisePersonalize appExercisePersonalize = this.getById(req.getPersonalizeId());
        if (Objects.isNull(appExercisePersonalize)){
            throw new RecordNotFoundException();
        }

        appExercisePersonalize.setPersonalizeId(req.getPersonalizeId().intValue());
        appExercisePersonalize.setUserId(req.getUserId());
        appExercisePersonalize.setHeight(req.getHeight());
        appExercisePersonalize.setNowBodyId(req.getNowBodyId());
        appExercisePersonalize.setTargetBody(req.getTargetBody());
        appExercisePersonalize.setDifficultyId(req.getDifficultyId());
        appExercisePersonalize.setWeight(req.getWeight());
        appExercisePersonalize.setBmi(req.getBmi());
        appExercisePersonalize.setAthleticAbility(req.getAthleticAbility());
        appExercisePersonalize.setConsume(req.getConsume().toString());
//        BeanUtils.copyProperties(req, appExercisePersonalize);
        return this.updateById(appExercisePersonalize);
    }

}




